<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
    </y-table>
    <y-form-dialog :title="formOptions.title" ref="dialogFormRef" :form-options="formOptions"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="formOptions.title" ref="dialogInfoRef" :form-options="detailFormConfig"
      @confirm="_ => { }"></y-form-dialog>
  </div>
</template>

<script>

import {
  getDepartmentList, updateDepartment,
  bathDeleteDepartment, addDepartment, getDepartmentCode
} from '@/api/base/department' // 接口

import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  data() {
    return {
      // 表格配置
      listOptions: {
        // 导出
        exportConfig: { fileName: '系所信息导出', moudle: 'XSXXDC' },
        // 导入
        importConfig: { fileName: '系所信息导入', module: 'XSXXDR' },
        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getDepartmentList,
        // 表单配置
        formOptions: {
          items: [
            {
              field: 'collegeCode', title: '院所名称',
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'college_list_easy'
                }
              }
            },
            {
              field: 'deptCode', title: '系所代码 | 名称',
              itemRender: {
                name: 'VxeInput'
              }
            },
            {
              field: 'deptManagerName', title: '系所负责人姓名',
              itemRender: {
                name: 'VxeInput'
              }
            }
          ]
        },
        // 表格配置
        tableOptions: {
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增', code: 'add', status: 'primary', icon: 'vxe-icon-add' },
              { name: '批量删除', code: 'batchDelete', status: 'danger', icon: 'vxe-icon-delete' }
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'checkbox', width: 60 },
            { type: 'seq', width: 60 },

            { field: 'collegeName', title: '所属院名' },
            { field: 'deptCode', title: '系所代码' },
            { field: 'deptName', title: '系所名称' },
            { field: 'deptManagerName', title: '系所负责人姓名' },
            { field: 'deptManagerOffice', title: '系所负责人办公地点' },
            { field: 'deptManagerContact', title: '系所负责人联系电话' },
            { field: 'deptManagerEmail', title: '系所负责人电子邮箱' },
            { field: 'deptMemo', title: '备注', visible: false },
            { field: 'orderNum', title: '排序号' },

            {
              title: '操作',
              width: 130,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  {
                    content: '更多', dropdowns: [
                      { content: '详情', name: 'info' },
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: {
                  click: ({ name, row }) => {
                    switch (name) {
                      case 'edit':
                        this.openFormDialog({ row, refName: 'dialogFormRef' })
                        break
                      case 'delete':
                        this.deleteRow({ row, deleteMethod: (row) => this.deleteById(row) })
                        break
                      case 'info':
                        this.openFormDialog({ row, refName: 'dialogInfoRef' })
                        break
                      default:
                        break
                    }
                  }
                }
              }
            }
          ]
        }
      },
      formOptions: {
        title: '系所信息',
        titleWidth: 160,
        items: [
          {
            required: true, field: 'collegeCode', title: '院所名称',
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'college_list_easy'
              }
            }
          },
          {
            required: true, field: 'deptCode', span: 12, title: '系所代码', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: 'autoDeptCode', span: 12,
            itemRender: {
              name: 'VxeButtonGroup',
              options: [
                { name: 'autoDeptCode', content: '系统自动生成', status: 'primary' }
              ],
              events: {
                click: (slotParams, { name }) => {
                  if (name === 'autoDeptCode'
                    && !slotParams.data.tid
                    && slotParams.data.collegeCode) {
                    getDepartmentCode(slotParams.data.collegeCode).then(res => {
                      if (res.status) {
                        this.$set(slotParams.data, 'deptCode', res.data)
                      }
                    })
                  }
                }
              }
            }
          },
          {
            required: true, field: 'deptName', title: '系所名称', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            required: true, field: 'deptManagerName', title: '系所负责人姓名', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            required: true, field: 'deptManagerOffice', title: '系所负责人办公地点', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            required: true, field: 'deptManagerContact', title: '系所负责人联系电话', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            required: true, field: 'orderNum', title: '排序号', itemRender: {
              name: 'VxeInput',
              props: { type: 'number' }
            }
          },
          {
            field: 'deptCodeInc', title: '数据中心单位编码', itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: 'deptManagerEmail', title: '系所负责人电子邮箱', itemRender: {
              name: 'VxeInput'
            }, rules: [{
              pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
              message: '请输入正确的邮箱格式'
            }]
          },
          {
            field: 'deptMemo', title: '备注', itemRender: {
              name: 'VxeTextarea'
            },
            rules: [{
              max: 2000,
              message: '请限制在2000字内'
            }]
          }
        ]
      }
    }
  },
  computed: {
    detailFormConfig() {
      return {
        ...this.formOptions,
        border: true,
        items: this.formOptions.items.filter(d => d.field).map(({ field, title }) => {
          return { field, title }
        })
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'add':
          // 执行添加操作，打开表单对话框
          this.openFormDialog({ row: null, refName: 'dialogFormRef' })
          break
        case 'batchDelete':
          // 批量删除
          let checkboxRecords = this.getCheckboxRow()
          if (checkboxRecords.length === 0) {
            this.$message.warning('请先选择要删除的记录')
            return
          }
          this.$confirm('确认删除选中的记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(checkboxRecords)
          })
          break
        default:
          break
      }
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.tid) {
        return updateDepartment(form)
      } else {
        return addDepartment(form)
      }
    },
    // 删除
    deleteById(row) {
      bathDeleteDepartment(row.tid || row.map(item => item.tid).join(',')).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    }
  }
}
</script>

<style lang="scss" scoped></style>
